from web.Script.ScriptTools import Request


class ScriptPic:
    def __init__(self):
        self.YyRequest = Request.RequestTools()
        self._domain = 'https://pic.netbian.com'

    # 公共函数: 获取分类
    def get_category(self):
        responses = []
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = self._domain, encoding = 'gbk'))
        a = etree_str.xpath('//*[@class="nav-m clearfix tran"]')
        b = etree_str.xpath('//*[@class="classify clearfix"]/a')
        for obj in b:
            responses.append({
                "name": obj.xpath('./text()')[0],
                "link": self._domain + obj.xpath('./@href')[0]
            })
        for obj in a:
            for obj1 in obj.xpath('./a'):
                responses.append({
                    "name": obj1.xpath('./text()')[0],
                    "link": self._domain + obj1.xpath('./@href')[0]
                })
        return responses

    # 公共函数: 获取图片Item
    def _get_pic_item(self, lis):
        responses = []
        for obj in lis:
            response = {
                "name": obj.xpath('./a/img/@alt')[0],
                "link": self._domain + obj.xpath('./a/@href')[0],
                "img": self._domain + obj.xpath('./a/img/@src')[0]
            }
            responses.append(response)
        return responses

    # 公共函数: 获取分页数据
    def _get_page(self, etree_str):
        res = {
                "min_page": 0,
                "this_page": 0,
                "page_list": []
            }
        if len(etree_str.xpath('//*[@class="page"]/b/text()')) == 0:
            return res
        responses = []
        min_page = 0
        this_page = etree_str.xpath('//*[@class="page"]/b/text()')[0]
        lis = etree_str.xpath('//*[@class="page"]/a')
        for obj in lis:
            try:
                page_num = int(obj.xpath('./text()')[0])
                min_page = page_num
                responses.append({
                    "name": page_num,
                    "link": self._domain + obj.xpath('./@href')[0]
                })
            except ValueError as e:
                continue
        res["min_page"] = min_page
        res["this_page"] = this_page
        res['page_list'] = responses
        return res

    # 爬虫主函数
    def run(self, theme = '4kdongman'):
        etree_str = self.YyRequest.get_html_tree(
            self.YyRequest.get_html(url = self._domain + f'/{theme}', encoding = 'gbk'))
        responses = self._get_pic_item(etree_str.xpath('//*[@class="clearfix"]/li'))
        pages = self._get_page(etree_str)
        return {
            "name": theme,
            "page": pages,
            "pic_list": responses
        }

    # 搜索图片
    def search(self, keyword):
        etree_str = self.YyRequest.get_html_tree(
            self.YyRequest.get_html(url = self._domain + f'/e/search/index.php', encoding = 'gbk', data = {
                'submit': '',
                'keyboard': keyword.encode('gbk'),
                "tempid": 1,
                "tbname": "photo",
                "show": 'title'
            },
                                    method = 'post'))
        if len(etree_str.xpath('//*[@class="search-no"]')) == 1:
            return {
                "name": keyword,
                "page": {
                    "min_page": 0,
                    "this_page": 0,
                    "page_list": []
                },
                "pic_list": []
            }
        responses = self._get_pic_item(etree_str.xpath('//*[@class="clearfix"]/li'))
        pages = self._get_page(etree_str)
        return {
            "name": keyword,
            "page": pages,
            "pic_list": responses
        }

    # 获取原图
    def get_original_pic(self, link):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = link, encoding = 'gbk'))
        img = self._domain + etree_str.xpath('//*[@id="img"]/img/@src')[0]

        title = etree_str.xpath('//*[@id="img"]/img/@alt')[0]

        infos = []
        for obj in etree_str.xpath('//*[@class="infor"]/p'):
            if len(obj.xpath('./span/a/text()')) > 0:
                infos.append({
                    "name": obj.xpath('./text()')[0],
                    "value": obj.xpath('./span/a/text()')[0],
                    "link": self._domain + obj.xpath('./span/a/@href')[0]
                })
                continue
            infos.append({
                "name": obj.xpath('./text()')[0],
                "value": obj.xpath('./span/text()')[0]
            })
        return {
            "title": title,
            "img": img,
            "infos": infos
        }


if __name__ == '__main__':
    script = ScriptPic()
    print(script.search("高中生"))

